﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace CodeBuilder
{
    public class DatabaseService
    {
        public string ConnectionString { get; set; }

        public string NameSpace { get; set; }

        public List<Table> Tables { get; set; } = new List<Table>();

        public BindingSource Source { get; set; } = new BindingSource();
        public string Provider { get;  set; }

        public void Load()
        {
            if (string.IsNullOrWhiteSpace(ConnectionString))
            {
                MessageBox.Show("请先选取数据库连接");
                return;
            }
            var loader = new DatabaseLoader();
            loader.Provider = this.Provider;
            loader.ConnectionString = ConnectionString;
            loader.Load();
            this.Tables = loader.Tables;
            this.Source = new BindingSource(this.Tables, null);
            MessageBox.Show("加载成功");
        }

        public string BuildClass(Table table)
        {
            //{1}
            StringBuilder defaultValue = new System.Text.StringBuilder();
            StringBuilder items = new System.Text.StringBuilder();
            string keyType = "";
            foreach (var item in table.Columns)
            {

                #region 判断是否是主键，并且是多主键
                if (item.IsPrimary)
                {
                    keyType = item.CLRType;
                }
                #endregion
                else
                {
                    items.Append("\t/// <summary>");
                    items.Append(System.Environment.NewLine);
                    items.Append(string.Format("\t///{0}", item.Description));
                    items.Append(System.Environment.NewLine);
                    items.Append("\t/// </summary>");
                    items.Append(System.Environment.NewLine);
                    if (!string.IsNullOrWhiteSpace(item.Description))
                    {
                        items.Append(string.Format("\t[Display(Name = \"{0}\")]", item.Description));
                        items.Append(System.Environment.NewLine);
                    }
                    items.Append(string.Format("\tpublic {0}{1} {2} {{get;set;}}", item.CLRType,item.CLRType!="string"&&item.IsNullable?"?":"", item.ColumnName));
                    items.Append(System.Environment.NewLine);
                }
            }
            return string.Format(Resource.ClassTemplete, NameSpace, table.Entity, keyType, defaultValue.ToString(), items.ToString());
        }
    }
}
